import { Controller, Get } from '@nestjs/common';
import {
  HealthCheckService,
  HttpHealthIndicator,
  TypeOrmHealthIndicator,
  HealthCheck,
  HealthCheckResult,
} from '@nestjs/terminus';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { ConfigService } from '@nestjs/config';
import { HealthService } from './health.service';

@ApiTags('健康检查')
@Controller('health')
export class HealthController {
  constructor(
    private readonly health: HealthCheckService,
    private readonly http: HttpHealthIndicator,
    private readonly db: TypeOrmHealthIndicator,
    private readonly healthService: HealthService,
    private readonly configService: ConfigService,
  ) {}

  @Get()
  @ApiOperation({ summary: '基础健康检查' })
  @ApiResponse({
    status: 200,
    description: '健康检查结果',
    schema: {
      type: 'object',
      properties: {
        status: { type: 'string', example: 'ok' },
        info: { type: 'object' },
        error: { type: 'object' },
        details: { type: 'object' },
      },
    },
  })
  @HealthCheck()
  check(): Promise<HealthCheckResult> {
    return this.health.check([
      () => this.db.pingCheck('database'),
      () => this.healthService.redisHealthIndicator(),
    ]);
  }

  @Get('detailed')
  @ApiOperation({ summary: '详细健康检查' })
  @ApiResponse({
    status: 200,
    description: '详细健康检查结果',
  })
  @HealthCheck()
  detailedCheck(): Promise<HealthCheckResult> {
    return this.health.check([
      () => this.db.pingCheck('database'),
      () => this.healthService.redisHealthIndicator(),
      () => this.healthService.memoryHealthIndicator(),
      () => this.healthService.diskHealthIndicator(),
      () => this.healthService.websocketHealthIndicator(),
    ]);
  }

  @Get('readiness')
  @ApiOperation({ summary: '就绪检查' })
  @ApiResponse({
    status: 200,
    description: '应用就绪状态',
  })
  @HealthCheck()
  readinessCheck(): Promise<HealthCheckResult> {
    return this.health.check([
      () => this.db.pingCheck('database'),
      () => this.healthService.redisHealthIndicator(),
      () => this.healthService.applicationReadinessIndicator(),
    ]);
  }

  @Get('liveness')
  @ApiOperation({ summary: '存活检查' })
  @ApiResponse({
    status: 200,
    description: '应用存活状态',
  })
  @HealthCheck()
  livenessCheck(): Promise<HealthCheckResult> {
    return this.health.check([
      () => this.healthService.applicationLivenessIndicator(),
    ]);
  }

  @Get('metrics')
  @ApiOperation({ summary: '应用指标' })
  @ApiResponse({
    status: 200,
    description: '应用性能指标',
  })
  async getMetrics() {
    return await this.healthService.getApplicationMetrics();
  }

  @Get('status')
  @ApiOperation({ summary: '应用状态' })
  @ApiResponse({
    status: 200,
    description: '应用运行状态',
  })
  async getStatus() {
    return await this.healthService.getApplicationStatus();
  }
}
